#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>

static void process(const char *path)
{
	struct dirent *entry;
	DIR *dir = opendir(path);
	char *text = malloc(4096);

#ifdef __DJGPP__
	_djstat_flags |=
		_STAT_INODE | _STAT_EXEC_EXT | _STAT_EXEC_MAGIC | _STAT_DIRSIZE |
		_STAT_ROOT_TIME | _STAT_WRITEBIT;
#endif

	/* Look through all files in the directory */
	while ((dir) && ((entry = readdir(dir)) != 0)) {
		char sysbuffer[4096];
		char newname[1024];
		char *ptr = newname;
		struct stat sbuf;
		int changed = 0;

		/* Skip traversal directories */
		if (entry->d_name[0] == '.')
			continue;

		strcpy(text, path);
		strcat(text, "\\");
		strcat(text, entry->d_name);

		if (stat(text, &sbuf) != 0)
			continue;

		/* Recurse sub-directories */
		if (S_ISDIR(sbuf.st_mode))
			process(text);

		strcpy(newname, entry->d_name);
		while (*ptr) {
			char c = *ptr;

			*ptr = tolower(*ptr);

			if (c != *ptr)
				changed = 1;

			++ptr;
		}

		strcpy(sysbuffer, path);
		strcat(sysbuffer, "\\");
		strcat(sysbuffer, newname);

		if (changed) {
			printf("%s\n", sysbuffer + 2);
			rename(text + 2, sysbuffer + 2);
		}
	}

	free(text);

	if (dir)
		closedir(dir);
}

int main(int argc, char *argv[])
{
	char prepath[4096];

	strcpy(prepath, ".");
	if (argc > 1) {
		strcat(prepath, "\\");
		strcat(prepath, argv[1]);
	}

	process(prepath);

	return EXIT_SUCCESS;
}
